<template>
  <div style="text-align: right">
    <el-upload
      :http-request="customUpload"
      :on-change="KnowledgeFiles"
      :show-file-list="false"
    >
      <el-button
        type="primary"
        color="#626aef"
        :icon="Plus"
        style="margin-right: 12px"
      >
        新增知识
      </el-button>
    </el-upload>
  </div>

  <el-table
    :data="tableData"
    style="width: 100%"
    :row-class-name="tableRowClassName"
    :row-style="setRowStyle"
    empty-text="暂无数据"
  >
    <el-table-column label="文件名称" prop="file_name" />
    <el-table-column label="更新时间">
      <template #default="scope">
        {{ formatDate(scope.row.update_date) }}
      </template>
    </el-table-column>
    <el-table-column label="文件大小">
      <template v-slot="scope">
        {{ formatFileSize(scope.row.file_size) }}
      </template>
    </el-table-column>
    <el-table-column label="文件状态" prop="state">
      <!-- 增加逻辑处理 -->
      <template #default="scope">
        <el-tag :type="tagFileState(scope.row.state)" disable-transitions>{{
          fileState(scope.row.state)
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" placeholder="搜索" @input="KnowledgeFiles" />
      </template>
      <template #default="scope">
        <!-- 新增按钮操作 -->
        <el-button
          @click="handleEdit(scope.$index, scope.row)"
          :disabled="scope.row.state === 1 ? false : true"
        >
          处理
        </el-button>
        <el-popconfirm
          title="删除后无法恢复哟！"
          @confirm="handleDelete(scope.$index, scope.row)"
        >
          <template #reference>
            <el-button type="danger"> 删除 </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <!-- 文件处理抽屉 -->
  <form-drawer
    ref="registerFormDrawerRef"
    title="处理文件"
    size="34%"
    confirmText="启动处理"
    destroyOnClose
    @submit="registerOnSubmit"
  >
    <el-form
      :model="registerForm"
      ref="registerFormRef"
      :rules="registerRules"
      label-width="100px"
      size="small"
      label-position="top"
    >
      <el-form-item prop="split_size" label="分词大小">
        <el-input-number
          size="large"
          v-model="registerForm.split_size"
          controls-position="right"
          min=30
          max=4096
          style="width: 30%"
        />
      </el-form-item>
      <el-form-item
        prop="file_extract_id"
        label="文本内容提取服务"
        style="width: 30%"
      >
        <el-select
          v-model="registerForm.file_extract_id"
          filterable
          size="large"
          :name="fileExtractSearch"
          :filter-method="remoteMethod"
          :loading="fileExtractLoadding"
          loading-text="正在努力寻找"
          no-data-text="臣妾支持不了哇"
          no-match-text="臣妾支持不了哇"
        >
          <el-option
            v-for="item in fileExtractData"
            :key="item.id"
            :label="item.model_name_zh"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="split_str" label="分词字符" style="width: 30%">
        <el-select
          v-model="registerForm.split_str"
          filterable
          allow-create
          default-first-option
          size="large"
          :reserve-keyword="false"
          placeholder="分词字符"
          style="width: 100%"
        >
          <el-option
            v-for="item in split_str_options"
            :key="item.name"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </form-drawer>
</template>

<script setup>
import FormDrawer from '~/components/FormDrawer.vue' // 解决会默认直接展示的问题
import { Search, Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import {
  KnowledgeFileList,
  KnowledgeFileDelete,
  KnowledgeFileUpload,
  TextExtractionServer
} from '~/api/manager'
import { ElLoading } from 'element-plus'
import { toast } from '~/composables/util'
import { KnowledgeFileHandleManger } from '~/composables/knowledgeManger'
import { tr } from 'element-plus/es/locale/index.mjs'

const {
  formDrawerRef: registerFormDrawerRef,
  formRef: registerFormRef,
  form: registerForm,
  onSubmit: registerOnSubmit,
  rules: registerRules,
  openRegisterForm
} = KnowledgeFileHandleManger()

const tableData = ref([])
const route = useRoute()
const page = ref(1)
const limit = ref(10)
const search = ref('')
console.log('router', route)
const knowledge_id = ref(route.params.id)
console.log('knowledge_id', knowledge_id.value)
const file_id = ref('')
const split_str_options = ref([
  {
    "name": "换行",
    "value": "\n"
  },
  {
    "name": "空格",
    "value": " "
  },
  {
    "name": "逗号",
    "value": ","
  },
  {
    "name": "分号",
    "value": ";"
  },
  {
    "name": "冒号",
    "value": ":"
  },
  {
    "name": "制表符",
    "value": "\t"
  }
])


// 文本提取部分
const fileExtractPage = ref(1)
const fileExtractLimit = ref(10)
const fileExtractSearch = ref('')
const fileExtractData = ref([])
const fileExtractCount = ref(0)
const fileExtractLoadding = ref(false)

const KnowledgeFiles = async () => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  KnowledgeFileList({
    knowledge_id: knowledge_id.value,
    page: page.value,
    limit: limit.value,
    name: search.value
  })
    .then((res) => {
      console.log('res', res)
      tableData.value = res.data
    })
    .finally(() => {
      loadingInstance.close()
    })
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // Months are 0-based
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const setRowStyle = (row, index) => {
  return {
    height: '50px'
  }
}

const formatFileSize = (bytes) => {
  console.log('bytes', bytes)
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const fileState = (state) => {
  const stateMap = {
    1: '等待处理',
    2: '处理中',
    3: '处理完成',
    4: '处理失败'
  }
  return stateMap[state] || '未知状态'
}

const tagFileState = (state) => {
  const stateMap = {
    1: 'primary',
    2: 'success',
    3: 'success',
    4: 'danger'
  }
  return stateMap[state] || 'unknown'
}

const handleDelete = (index, row) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  KnowledgeFileDelete(knowledge_id.value, row.id)
    .then((res) => {
      console.log('res', res)
    })
    .finally(() => {
      loadingInstance.close()
      KnowledgeFiles()
    })
}

// 文件上传
const customUpload = (options) => {
  const loadingInstance = ElLoading.service({ fullscreen: true })
  const { action, file, data, headers, onProgress, onSuccess, onError } =
    options

  KnowledgeFileUpload(file, knowledge_id.value)
    .then((res) => {
      toast('上传成功', 'success')
      console.log('res', res)
      onSuccess(res) // 通知组件上传成功
    })
    .catch((err) => {
      toast('上传失败', 'error')
      console.error('上传失败:', err)
      onError(err) // 通知组件上传失败
    })
    .finally(() => {
      loadingInstance.close() // 关闭加载状态
      KnowledgeFiles()
    })
}

// 文件处理
const handleEdit = async (index, row) => {
  file_id.value = row.id
  console.log('row', row)
  registerForm.file_id = file_id.value
  registerForm.knowledge_id = knowledge_id.value
  registerForm.split_size = Number(registerForm.split_size);
  openRegisterForm()
}

// 文本抽取服务
const handleTextExtraction = async() => {
  fileExtractLoadding.value = true
  TextExtractionServer({
    page: fileExtractPage.value,
    limit: fileExtractLimit.value,
    name: fileExtractSearch.value
  })
    .then((res) => {
      console.log('res', res)
      fileExtractData.value = res.data
      fileExtractCount.value = res.count

    }).finally(() => {
      fileExtractLoadding.value = false
    })
}

// 远程搜索方法
const remoteMethod = async (query) => {
  fileExtractPage.value = 1
  fileExtractLimit.value = 10
  fileExtractCount.value = 0
  fileExtractSearch.value = query
  await handleTextExtraction()
  fileExtractSearch.value = ''
  console.log(selectEmbeddingServer.value)
}

onMounted(() => {
  KnowledgeFiles()
})
</script>

<style>
/* 设置表格行高 */
.tableRowClassName {
  height: 600px; /* 设置行高 */
  line-height: 60px; /* 设置行内文字垂直居中 */
}
</style>
